package com.demo.deal_service.util;

import java.io.*;

public class FileUtil {
    /**
     * 根据传入的文件与输入流来写入文件
     *
     * @param file
     * @param inputStream
     * @throws IOException
     */
    public static void writeFileByInputStream(File file, InputStream inputStream) throws IOException {
        int bufferSize = 1024;
        char[] buffer = new char[bufferSize];
        byte[] byteBuffer = new byte[bufferSize];
        int bytesWritten = 0; //已经写入的字节数
        int bytesCount = 0; //当前读取字节数
        BufferedWriter bufferedWriter = null;
        BufferedReader bufferedReader = null;

        try {
//            bufferedWriter = new BufferedWriter(new FileWriter(file)); //可能抛出io异常
//            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

//            while ((bytesCount = bufferedReader.read(buffer)) != -1 ){
//                bufferedWriter.write(buffer, 0, bytesCount); //可能抛出io异常
//                bytesWritten += bytesCount;
//            }

            BufferedInputStream bis = new BufferedInputStream(inputStream);
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));

            while ((bytesCount = bis.read(byteBuffer)) != -1 ){
                bos.write(byteBuffer, 0, bytesCount); //可能抛出io异常
                bytesWritten += bytesCount;
            }
        } finally {

        }

    }
}
